package com.step.ems.common

import android.content.Context
import com.google.gson.GsonBuilder
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter
import com.step.ems.api.ApiService
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton

@InstallIn(SingletonComponent::class)
@Module
class Di {
    companion object {
        // const val BASE_URL = "https://mock.apifox.com/m1/4445247-4091078-default/"
        const val BASE_URL = "http://2024katherine.zicp.fun:30090/mgmt-elevator-central/"
        // const val BASE_URL = "http://124.217.246.160:30090/mgmt-elevator-central/"
        val noAuthUrls = listOf("consumer/login", "consumer/refreshToken")
    }

    @Provides
    @Singleton
    fun providePhotoUriManager(@ApplicationContext appContext: Context): PhotoUriManager {
        return PhotoUriManager(appContext)
    }

    @Singleton
    @Provides
    fun provideApiService(storeUtil: DataStoreUtil): ApiService {
        val logger = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY }

        val client = OkHttpClient.Builder()
            .addInterceptor { chain ->
                val accessToken = runBlocking { storeUtil.getAccessToken() }
                var request = chain.request()
                val path = request.url.toString()
                val noAuth = noAuthUrls.any {
                    path.contains(it)
                }
                if (!noAuth && accessToken != null) {
                    request = request.newBuilder()
                        .addHeader("Authorization", "bearer $accessToken")
                        .build()
                }
                chain.proceed(request)
            }
            .addInterceptor(logger)
            .build()

        val gson = GsonBuilder()
            // 注册一个自定义的序列化器，用于将null转换为空字符串
            .registerTypeAdapter(String::class.java, StringNullAdapter())
            .create()

        return Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(ApiService::class.java)
    }
}

class StringNullAdapter : TypeAdapter<String>() {
    override fun write(out: JsonWriter, value: String?) {
        out.value(value ?: "")
    }

    override fun read(jsonReader: JsonReader): String {
        if (jsonReader.peek() == JsonToken.NULL) {
            jsonReader.nextNull()
            return ""
        }
        return jsonReader.nextString()
    }
}